// store.ts
import { InjectionKey } from 'vue'
import { createStore, Store, useStore as baseUseStore } from 'vuex'
import { getTotalDictItems } from '@/api/dict'
import { ACCESS_TOKEN, ID_TOKEN, REFRESH_TOKEN } from '@/utils/constant'
import { useStorage } from 'vue3-storage'
import { DictItem, SysUser } from '@/config/common'
import { getTokenByCode, getUserInfo } from '@/api/auth'

const storage = useStorage()

// 为 store state 声明类型
export interface CustomStore {
  dict: { [key: string]: DictItem[]; };
  userInfo: SysUser | null;
  isSuperAdmin: false;
  permissions: string[];
}

// 定义 injection key
export const key: InjectionKey<Store<CustomStore>> = Symbol('store key')

// @ts-ignore
// @ts-ignore
export const store = createStore<CustomStore>({
  state: {
    dict: {
      USER_STATUS: [
        {
          itemValue: '1',
          itemText: '正常'
        },
        {
          itemValue: '2',
          itemText: '停用'
        }
      ],
      FILL_STATUS: [
        {
          itemValue: '0',
          itemText: '未填报'
        },
        {
          itemValue: '1',
          itemText: '已保存'
        },
        {
          itemValue: '2',
          itemText: '已提交'
        }
      ],
      ORG_TYPE: [
        {
          itemValue: 'OT01',
          itemText: '教育局'
        },
        {
          itemValue: 'OT02',
          itemText: '学校'
        }
      ],
      FIELD_TYPE: [
        {
          itemValue: 'FT01',
          itemText: '文本'
        },
        {
          itemValue: 'FT02',
          itemText: '数字'
        },
        {
          itemValue: 'FT03',
          itemText: '百分比'
        },
        {
          itemValue: 'FT04',
          itemText: '是否'
        },
        {
          itemValue: 'FT05',
          itemText: '选项'
        },
        {
          itemValue: 'FT06',
          itemText: '字典'
        }
      ]
    },
    userInfo: null,
    isSuperAdmin: false,
    permissions: []
  },
  getters: {
    dict: (state) => state.dict,
    dictText: (state) => (code: string, value: string) => {
      return (state.dict[code] || []).filter(e => e.itemValue === value).map(e => e.itemText)[0] || ''
    },
    userInfo: state => state.userInfo,
    isSuperAdmin: state => state.isSuperAdmin,
    permissions: state => state.permissions,
    orgId: state => (state.userInfo && state.userInfo.roleCode === 'ROLE_SCHOOL' && state.userInfo.orgId) || ''
  },
  mutations: {
    SET_DICT_DATA (state, data) {
      state.dict[data.code] = data.data
    },
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo
    },
    SET_IS_SUPER_ADMIN: (state, isSuperAdmin) => {
      state.isSuperAdmin = isSuperAdmin
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    }
  },
  actions: {
    async LoadDictData ({
      commit,
      state
    }, codes: string[]) {
      const dictCodes = codes.filter(
        (dictCode: string) => !state.dict[dictCode]
      )
      if (!dictCodes.length) {
        return state.dict
      }
      const list: DictItem[] = await getTotalDictItems(dictCodes)
      const obj: { [key: string]: DictItem[]; } = {}
      for (let i = 0; i < list.length; i++) {
        const code = list[i].dictCode as string
        if (!obj[code]) {
          obj[code] = []
        }
        obj[code].push(list[i])
      }
      Object.keys(obj).forEach((code) => {
        commit('SET_DICT_DATA', {
          code,
          data: obj[code]
        })
      })
      return state.dict
    },
    // async Login ({ commit }, user: UsernamePasswordToken) {
    //   const {
    //     username,
    //     password
    //   } = user
    //   const res = await getToken(username, password)
    //   storage.setStorageSync(ACCESS_TOKEN, res.access_token, 7 * 24 * 60 * 60 * 1000)
    //   // storage.setStorageSync(REFRESH_TOKEN, res.refresh_token, 7 * 24 * 60 * 60 * 1000)
    //   return res.access_token
    // },
    async CodeLogin ({ commit }, data) {
      const res = await getTokenByCode({
        ...data,
        redirect_uri: encodeURIComponent(import.meta.env.VITE_REDIRECT_URI)
      })
      storage.setStorageSync(ACCESS_TOKEN, res.accessToken, 7 * 24 * 60 * 60 * 1000)
      storage.setStorageSync(ID_TOKEN, res.idToken, 7 * 24 * 60 * 60 * 1000)
      storage.setStorageSync(REFRESH_TOKEN, res.refreshToken, 7 * 24 * 60 * 60 * 1000)
      return res.accessToken
    },
    // 获取用户信息
    async RefreshToken ({ commit }) {
      // @ts-ignore
      const res = await refreshToken(storage.getStorageSync(REFRESH_TOKEN) as string)
      storage.setStorageSync(ACCESS_TOKEN, res.accessToken, 7 * 24 * 60 * 60 * 1000)
      storage.setStorageSync(ID_TOKEN, res.idToken, 7 * 24 * 60 * 60 * 1000)
      storage.setStorageSync(REFRESH_TOKEN, res.refreshToken, 7 * 24 * 60 * 60 * 1000)
      return res.accessToken
    },
    // 获取用户信息
    async GetInfo ({ commit }) {
      // const [userInfo, permissions] = await Promise.all([getUserInfo(), getUserPermissions()])
      const userInfo = await getUserInfo()
      commit('SET_USER_INFO', userInfo)
      commit('SET_IS_SUPER_ADMIN', true)
      // commit('SET_PERMISSIONS', (permissions as SysPermission[]).map(e => e.permissionCode))
      return userInfo
    },
    // 登出
    async Logout ({ commit }) {
      commit('SET_USER_INFO', null)
      commit('SET_PERMISSIONS', [])
      storage.removeStorageSync(ACCESS_TOKEN)
      storage.removeStorageSync(ID_TOKEN)
      storage.removeStorageSync(REFRESH_TOKEN)
    }
  }
})

export function useStore () {
  return baseUseStore(key)
}
